package com.yang.externalizable;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * 
 * @author yang
 *
 * 2015年12月4日
 *
 *关于externalizable的使用
 */
public class Cat implements java.io.Externalizable {
	private String name;
	public Cat(){}
	public Cat(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	private int age;

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeObject(name);
		out.writeInt(age);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		name = (String) in.readObject();
		age = in.readInt()+1;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return name + "----" + age;
	}
	
	public static void main(String[] args) {
		Cat cat = new Cat("tom", 3);
		ObjectOutputStream objectOutputStream = null;
		ObjectInputStream inputStream = null;
		try {
			objectOutputStream = new ObjectOutputStream(new FileOutputStream("aa.txt"));
			objectOutputStream.writeObject(cat);
			objectOutputStream.flush();
			inputStream = new ObjectInputStream(new FileInputStream("aa.txt"));
			cat = (Cat) inputStream.readObject();
			System.out.println(cat);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			if(objectOutputStream != null){
				try {
					objectOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
